<?php
/**
 * 将md图片处理为本地，同时替换md文件为相对路径链接
 * 按文件夹
 */

$LIB = dirname(__FILE__);
require_once($LIB. "/vendor/autoload.php");

$options = getopt("s:d:", ['type:', 'mode:', 'withHost:']);
// var_dump($options);
$type = $options['type'] ?? ''; //md, html源文件类型
$mode = $options['mode'] ?? '1'; //1 down+replace下载并替换为相对链接 2down仅下载 3replace仅替换为相对链接
$withHost = $options['withHost'] ?? '0'; //下载的图片文件名是否带host前缀，默认否
$src = $options['s'] ?? '';
$dst = $options['d'] ?? $src . "/output";
if (empty($type) || empty($src) || empty($dst) || empty($mode)) {
    exit("usage: php $argv[0] -s src_dir [-d dst_dir] --type [md,html] [--mode 1,2,3]");
}

if (!is_dir($src)) {
    exit($src . " 不存在");
}

$img_short_dir = "images/";
$img_dir = $dst . "/" . $img_short_dir;
if (!is_dir($dst)) {
    @mkdir($dst, 0755, true);
    @mkdir($img_dir, 0755, true);
}


$files = glob("{$src}/*.{$type}");
// $files = glob("{$src}/*.*");
// print_r($files);
foreach($files as $file) {
    // echo $file;
    $content = file_get_contents($file);
    $content = replaceOtherPicTags($content);
    $contentLast = matchMdPic($type, $mode, $content, $img_dir, $img_short_dir, $withHost);
    // output
    file_put_contents($dst . "/". basename($file), $contentLast);
    info($file . " convert ok");
    // exit;
}


function replaceOtherPicTags($content){
    return str_replace(["<figure>", "</figure>", "<figcaption>", "</figcaption>"], " ", $content);
}

/**
 * ![](https://static001.geekbang.org/resource/image/fe/79/feaf5c9f1b5dd8c4a1546344c67e3979.png)![](https://static001.geekbang.org/resource/image/27/f6/278f19c944ae955de49575bca3fde0f6.png)
 * ![](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/7/14/16bee4480039a721~tplv-t2oaga2asx-image.image)
 * <img src="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/7/9/1647e75e1b3fba53~tplv-t2oaga2asx-image.image">
 */
function matchMdPic($type, $mode, $content, $img_dir, $img_short_dir, $withHost){
    if ($type == "md") {
        preg_match_all('/\((https?:\/\/(.*?)\.(image|awebp|png|jpg|gif|jpeg))\)/', $content, $pics, PREG_SET_ORDER );
    } else { //html
        preg_match_all('/img src=\"(https?:\/\/(.*?)\.(image|awebp|png|jpg|gif|jpeg))\"/', $content, $pics, PREG_SET_ORDER );
    }
    // print_r($pics);exit;
	foreach($pics as $pic){
		$url = $pic[1];
		$path_parts  =  pathinfo($url);
		$extension = @$path_parts['extension'] ? : 'jpg';
        if (!in_array($extension, ["jpg", "jpeg", "png", "gif"])) {
            $extension = 'jpg';
        }
 
		if(!preg_match('/^http/', $url)){
			$url = 'http://'.$url;
		}
		
		print_r($url."  ok\n");
		
        $filename = md5($url).".".$extension; //图片文件名称
        if ($withHost) {
            $urlArr= parse_url($url);
            $filename =  $urlArr['host'] . "_". $filename;
        }
        $img_file_path = $img_short_dir . $filename; //图片存储目录

        switch ($mode) {
            case 2: // 2down仅下载 
                doDwonload($url, $img_dir , $filename);
                break;
            case 3: // 3replace仅替换为相对链接
                $content = getReplace($url, $img_file_path, $content);
                break;
            default: // down+replace下载并替换为相对链接
                doDwonload($url, $img_dir , $filename);
                $content = getReplace($url, $img_file_path, $content);

        }
	}
	
	return $content;
}

function doDwonload($url, $img_dir , $filename)
{
    if(checkHttpStatus($url)){
        downPic($url, $img_dir , $filename);
    } else {
        error("bad img :". $url);
    }
}

function getReplace($url, $img_file_path, $content){
    // 替换md文件里为相对路径
    $content = str_replace($url, $img_file_path, $content);

    // 转换图片后一个括号换行的问题
    // $content = preg_replace('/\.(image|awebp|png|jpg|gif|jpeg)\n\)/s', '.$1)', $content);
    return $content;
}